package org.xin.security.component;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.xin.common.util.ClientUtil;
import org.xin.common.util.ip.IPUtil;
import org.xin.framework.component.CaptchaComponent;
import org.xin.framework.config.exception.CloudException;
import org.xin.security.pojo.bo.SecurityUser;
import org.xin.security.config.authentication.CustomAuthenticationManager;
import org.xin.security.pojo.bo.UserInfo;
import org.xin.security.service.ISysUserSecurityService;
import org.xin.security.pojo.form.UserLoginForm;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> 登录校验方法 </p>
 * @modified By：$
 * @version: $
 */
@Slf4j
@Component
public class UserLoginComponent {
    @Autowired
    private CustomAuthenticationManager authenticationManager;
    @Autowired
    private TokenComponent tokenComponent;
    @Autowired
    private CaptchaComponent captchaComponent;
    @Autowired
    private PermissionMangerComponent permissionMangerComponent;
    @Autowired
    private ISysUserSecurityService userSecurityService;


    /**
     * 登录验证
     *
     * @return 结果
     */
    public Dict login(UserLoginForm form) {
        String username = form.getUsername(), password = form.getPassword(), uuid = form.getUuid(), code = form.getCode();

        captchaComponent.validateCaptcha(username, code, uuid);
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (CloudException e) {
            e.printStackTrace();
            throw new CloudException(e);
        }
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        // 生成token
        return tokenComponent.createToken(securityUser);
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(UserInfo user) {
        user.setLoginIp(IPUtil.getIpAddr(ClientUtil.getRequest()));
        user.setLastLoginTime(DateUtil.now());
//        userService.updateUserProfile(user);
    }

    public Authentication getUserAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
